package graphics;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Vector;

import javax.imageio.ImageIO;

public class CreateImage {

    public static void createJpg(BufferedImage image, String path) {
        try {
            FileOutputStream fos = new FileOutputStream(path);
            BufferedOutputStream bos = new BufferedOutputStream(fos);

            /*
             * JPEGImageEncoder encodes buffers of image data into JPEG data
             * streams. Users of this interface are required to provide image
             * data in a Raster or a BufferedImage
             * 
             * JPEGCodec: This class is a factory for implementations of the
             * JPEG Image Decoder/Encoder.
             */
            ImageIO.write(image, "jpeg", bos);
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    public static void main(String args[]) {
        int width = 400, height = 200;
        int xLength = 300, yLength = 150;
        int count = 5;

        Vector<Integer> data = new Vector<Integer>();
        data.addElement(new Integer(100));
        data.addElement(new Integer(120));
        data.addElement(new Integer(150));
        data.addElement(new Integer(40));
        data.addElement(new Integer(5));

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        g.setColor(Color.white);
        g.fillRect(0, 0, width, height);
        g.setColor(Color.blue);
        // 画坐标轴
        g.drawLine(10, height - 10, 10, height - 10 - yLength);
        g.drawLine(10, height - 10, 10 + xLength, height - 10);

        int yTo;
        int yFrom = (Integer) (data.elementAt(0)).intValue();
        for (int i = 1; i < count; i++) {
            yTo = (Integer) (data.elementAt(i)).intValue();
            g.drawLine(10 + i * xLength / count, height - 10, 10 + i * xLength / count, height - 15); // 连线
            g.drawLine(10 + (i - 1) * xLength / count, yFrom, 10 + i * xLength / count, yTo);
            yFrom = yTo;
        }
        createJpg(image, "image.jpg");
    }
}